//
//  YAYIPatienInfoController.m
//  YAYIDoctor
//
//  Created by hxp on 16/4/29.
//  Copyright © 2016年 hxp. All rights reserved.
//

#import "YAYIPatienInfoController.h"
#import "YAYIPatientRecoderCell.h"
#import "YAYIPatientInfoModel.h"
#import "YAYIOrderPatientModel.h"
#import "YAYIModelView.h"
#import "YAYIGroupModel.h"
#import "YAYIAvatarCell.h"
#import "YAYIPatientInfoCell.h"
#import "YAYIAppointListCell.h"
@interface YAYIPatienInfoController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *dataAry;
@property (nonatomic,strong)NSMutableArray *dataOrderAry;
@property (nonatomic,strong)UIView *bottomView;

/** 分页相关 */
@property (nonatomic, assign) NSInteger curPage;
@property (nonatomic, assign) NSInteger pageCount;

@end

@implementation YAYIPatienInfoController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.dataAry = [NSMutableArray array];
    self.dataOrderAry = [NSMutableArray array];
    self.title = @"基本信息";
    
    [self creatTableView];
    [self createBottomView];
    [self baseInfo];
    [self getPatientOrder];
    
    __block typeof(self) weakself = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [weakself getPatientOrder];
    }];
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        [weakself getMorePatientOrder];
    }];
    //    [self.tableView.mj_footer setAutomaticallyHidden:YES];
}


-(UIView *)tableViewHeaderView{
    
    UIView *headerView = [UIView  new];
    headerView.frame = CGRectMake(0, 0, SCREEN_width, 36);
    headerView.backgroundColor = [UIColor colorWithWhite:0.965 alpha:1];
    UILabel *title = [UILabel new];
    title.textColor = [UIColor grayColor];
    title.font = [UIFont systemFontOfSize:font14];
    title.frame = CGRectMake(20,8 , 100, 20);
    title.text = @"就诊信息";
    [headerView addSubview:title];
    return headerView;
}


-(void)createBottomView
{
    
    if (self.isAccepted) {
        self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        return;
    }
    
    if (self.bottomView == nil) {
        self.bottomView = [UIView  new];
        self.bottomView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:self.bottomView];
    }
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@(0));
        make.right.equalTo(@(0));
        make.top.mas_equalTo(self.view.mas_bottom).with.offset(-44);
        make.height.equalTo(@(44));
    }];
    
    // 线
    UIView *lineView = [[UIView alloc] init];
    lineView.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1];
    [self.bottomView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.top.mas_equalTo(0);
        make.width.mas_equalTo(SCREEN_width);
        make.height.mas_equalTo(0.5);
    }];
    
    
    CGFloat w = (SCREEN_width - 30 * 2 -40)/2.0;
    NSArray *titles = @[@"接 受",@"拒 绝"];
    
    
    for (int i =0; i< 2; i ++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.tag = i + 1;
        button.layer.cornerRadius = 5;
        button.layer.masksToBounds = YES;
        [button setBackgroundColor:YAYIColor(83, 165, 243)];
        [button addTarget:self action:@selector(addAction:) forControlEvents:UIControlEventTouchUpInside];
        [button setTitle:titles[i] forState:UIControlStateNormal];
        button.frame = CGRectMake(30 + (i * (w+40)) , 2, w , 35);
        button.centerY = 22;
        [self.bottomView addSubview:button];
    }
}

-(void)addAction:(UIButton *)sender
{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"id"] = [NSString stringWithFormat:@"%@", self.id];
    param[@"reportstate"] = [NSString stringWithFormat:@"%ld",sender.tag];
    
    YAYILog(@"param:%@", param);
    
    [YAYINetWorking  postJsonSerilizeWithURL:acceptBdPatient_url param:param finish:^(NSData *data, NSDictionary *dict, NSError *error,NSDictionary *responseError) {
        
        
        if (error == nil) {
            if ([dict[@"status"] isEqualToString:@"success"]) {
                
                NSString *message = sender.tag == 1 ? @"接受成功" : @"拒绝成功";
                [SVProgressHUD showSuccessWithStatus:message];
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.navigationController popViewControllerAnimated:YES];
                    
                    if ([self.delegate respondsToSelector:@selector(patienInfoAcceptOrDefine)]) {
                        [self.delegate patienInfoAcceptOrDefine];
                        
                    }
                });
                
            }else{
                
                NSString *message = dict[@"message"];
                [SVProgressHUD showSuccessWithStatus:message];
                
            }

        }else{
            NSString *message = responseError[@"message"];
            [SVProgressHUD showSuccessWithStatus:message];
        }
    }];
}


-(NSString *)gender:(NSString *)gender
{
    if ([gender intValue] == -1) {
        return @"女";
    }else if([gender intValue] == 0){
        return @"不详";
    }else{
        return @"男";
    }
  
}
-(void)creatTableView
{
    if (self.tableView ==  nil) {
        self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_width, SCREEN_height) style:UITableViewStyleGrouped];
        self.tableView.delegate = self;
        self.tableView.dataSource = self;
        self.tableView.tableFooterView = [UIView new];
        self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
        self.tableView.showsVerticalScrollIndicator = NO;
        [self.view addSubview:self.tableView];
        
        self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 44, 0);
    }
}

-(void)createDataSource:(YAYIPatientInfoModel *)model
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSMutableArray *group1 = [NSMutableArray array];
        NSMutableArray *group0 = [NSMutableArray array];
        YAYIGroupModel *group = [[YAYIGroupModel alloc] init];
        group.avatar = [NSString stringWithFormat:@"%@%@",API,model.avatar];
        group.name =model.fullname;
        group.phone = model.mobile;
        [group0 addObject:group];
        
        NSArray *titleAry = @[@"性别",@"年龄",@"邮箱",@"地址"];
        NSArray *name = @[[self gender:model.gender],[NSString  ageStr:model.birthday],[self email:model.email],[self addressStr:model.address]];
        for (int i = 0; i< name.count; i ++) {
            YAYIGroupModel *group = [[YAYIGroupModel alloc] init];
            group.title = titleAry[i];
            group.name = name[i];
            [group1  addObject:group];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.dataAry addObject:group0];
            [self.dataAry addObject:group1];
            [self.dataAry addObject:group0];
            [self.tableView reloadData];
        });
    });
}


-(NSString *)email:(NSString *)email
{
    if (email == nil) {
        return @"";
    }else{
        return email;
    }
}


-(NSString *)addressStr:(NSString *)address
{
    if (address == nil) {
        return @"";
    }else{
        return address;
    }

}


#pragma mark - 获取数据
-(void)baseInfo{
    
    YAYILog(@"userid:%@", self.userid);
    
    [YAYINetWorking getWithURL:patientDetail_url param:@{@"userid":self.userid} finish:^(NSData *data, NSDictionary *dict, NSError *error) {
        
        if (nil == error) {
            
            if ([dict[@"status"] isEqualToString:@"success"] && ![dict[@"data"] isKindOfClass:[NSNull class]]) {
                
                YAYILog(@"基本信息返回:%@", dict);
                NSDictionary *dic = dict[@"data"];
                
                
                YAYIPatientInfoModel *model = [YAYIPatientInfoModel new];
                [model setValuesForKeysWithDictionary:dic];
                [self createDataSource:model];
            }
        }else{
        
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:error.userInfo[@"com.alamofire.serialization.response.error.data"] options:NSJSONReadingMutableContainers error:nil];
            YAYILog(@"erro:%@", dict);
            [SVProgressHUD showImage:nil status:[NSString stringWithFormat:@"\n\n%@\n\n", dict[@"message"]]];
        }
        
    }];
    
}


-(void)getPatientOrder
{
    
    [self.dataOrderAry removeAllObjects];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userid"] = self.userid;
    
    [YAYINetWorking  getWithURL:patientOrders_url param:param finish:^(NSData *data, NSDictionary *dict, NSError *error) {
        
        if ([dict[@"status"] isEqualToString:@"success"]) {
           
            NSArray *data = dict[@"data"];
            for (NSDictionary *obj in data) {
                YAYIOrderPatientModel *model = [YAYIOrderPatientModel new];
                NSDictionary *ob = obj[@"snapshot"];
                [model.snapshot setValuesForKeysWithDictionary:ob];
                [model setValuesForKeysWithDictionary:obj];
                [self.dataOrderAry addObject:model];
            }
            
            self.curPage = 1;
            
            [self.tableView.mj_header endRefreshing];
            if (self.dataOrderAry.count < 10) {
                
                [self.tableView.mj_footer endRefreshing];
                self.tableView.mj_footer.hidden = YES;
            }else{
                [self.tableView.mj_footer setState:MJRefreshStateIdle];
                self.tableView.mj_footer.hidden = NO;
            }
            
            if (self.dataAry.count > 0) {
                [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:2] withRowAnimation:UITableViewRowAnimationNone];
            }
        }
    }];
}


-(void)getMorePatientOrder
{

    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userid"] = self.userid;
    param[@"currentPage"] = @(self.curPage + 1);
    
    [YAYINetWorking  getWithURL:patientOrders_url param:param finish:^(NSData *data, NSDictionary *dict, NSError *error) {
        
        YAYILog(@"就诊信息：%@", dict);
        if ([dict[@"status"] isEqualToString:@"success"]) {
            
            NSArray *data = dict[@"data"];
            for (NSDictionary *obj in data) {
                YAYIOrderPatientModel *model = [YAYIOrderPatientModel new];
                NSDictionary *ob = obj[@"snapshot"];
                [model.snapshot setValuesForKeysWithDictionary:ob];
                [model setValuesForKeysWithDictionary:obj];
                [self.dataOrderAry addObject:model];
            }
            
            self.curPage++;
            
            if (data.count < 10) {
                [self.tableView.mj_footer endRefreshing];
                self.tableView.mj_footer.hidden = YES;
            }else{
                [self.tableView.mj_footer endRefreshing];
            }
            
            if (self.dataAry.count > 0) {
                [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:2] withRowAnimation:UITableViewRowAnimationNone];
            }
        }
    }];
}


#pragma mark - 代理方法
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataAry.count ;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0){
        return [self.dataAry[section] count];
    }else if (section == 1){
        return [self.dataAry[section] count];
    }else if (section == 2){
        return self.dataOrderAry.count;
    }
    return 0;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        static NSString *identifer = @"avatarCell";
        YAYIAvatarCell *cell = [tableView dequeueReusableCellWithIdentifier:identifer];
        if (cell == nil) {
            cell = [[YAYIAvatarCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifer];
        }
        YAYIGroupModel *model = self.dataAry[indexPath.section][indexPath.row];
        [cell.avatar sd_setImageWithURL:[NSURL URLWithString:model.avatar] placeholderImage:[UIImage imageNamed:@"1"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            
        }];
        cell.phone.text = model.phone;
        cell.name.text =  model.name;
        cell.icon.hidden = YES;
        return cell;
    }else if (indexPath.section == 1){
        static NSString *identifer = @"identifer";
        YAYIPatientInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:identifer];
        if (cell == nil) {
            cell = [[YAYIPatientInfoCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifer];
        }
        
        YAYIGroupModel *model = self.dataAry[indexPath.section][indexPath.row];
        cell.title.text = model.title;
        cell.name.text = model.name;
        return cell;
    }else if(indexPath.section == 2){
        
        YAYIAppointListCell *cell = [YAYIAppointListCell cellWith:tableView];
        
        cell.model = self.dataOrderAry[indexPath.row];
        return cell;
    }
    return nil;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 87;
    }else if (indexPath.section ==1){
        return 48;
    }
    return 180;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 2) {
        return 36;
    }
    return 14;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 2) {
        return [self tableViewHeaderView];
    }
    return [UIView new];
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


@end
